
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>route: Go Coverage Report</title>
		<style>
			body {
				background: black;
				color: rgb(80, 80, 80);
			}
			body, pre, #legend span {
				font-family: Menlo, monospace;
				font-weight: bold;
			}
			#topbar {
				background: black;
				position: fixed;
				top: 0; left: 0; right: 0;
				height: 42px;
				border-bottom: 1px solid rgb(80, 80, 80);
			}
			#content {
				margin-top: 50px;
			}
			#nav, #legend {
				float: left;
				margin-left: 10px;
			}
			#legend {
				margin-top: 12px;
			}
			#nav {
				margin-top: 10px;
			}
			#legend span {
				margin: 0 5px;
			}
			.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }

		</style>
	</head>
	<body>
		<div id="topbar">
			<div id="nav">
				<select id="files">
				
				<option value="file0">/home/lihaowei/goWorkSpace/service-computing/hw9/route/routes.go (84.1%)</option>
				
				</select>
			</div>
			<div id="legend">
				<span>not tracked</span>
			
				<span class="cov0">not covered</span>
				<span class="cov8">covered</span>
			
			</div>
		</div>
		<div id="content">
		
		<pre class="file" id="file0" style="display: none">package route

import (
        "net/http"
        "net/url"
        "path/filepath"
        "regexp"
        "strings"
)

const (
        DELETE = "DELETE"
        GET    = "GET"
        POST   = "POST"
        PUT    = "PUT"
)

type route struct {
        method  string
        regex   *regexp.Regexp
        params  map[int]string
        handler http.HandlerFunc
}

type RouteMux struct {
        routes  []*route
        filters []http.HandlerFunc
}

func New() *RouteMux <span class="cov0" title="0">{
        return &amp;RouteMux{}
}</span>

// Get adds a new Route for GET requests.
func (m *RouteMux) Get(pattern string, handler http.HandlerFunc) <span class="cov8" title="1">{
        m.AddRoute(GET, pattern, handler)
}</span>

// Put adds a new Route for PUT requests.
func (m *RouteMux) Put(pattern string, handler http.HandlerFunc) <span class="cov0" title="0">{
        m.AddRoute(PUT, pattern, handler)
}</span>

// Del adds a new Route for DELETE requests.
func (m *RouteMux) Del(pattern string, handler http.HandlerFunc) <span class="cov0" title="0">{
        m.AddRoute(DELETE, pattern, handler)
}</span>

// Post adds a new Route for POST requests.
func (m *RouteMux) Post(pattern string, handler http.HandlerFunc) <span class="cov0" title="0">{
        m.AddRoute(POST, pattern, handler)
}</span>

// Adds a new Route for Static http requests.
// Serves static files from the specified directory
func (m *RouteMux) Static(pattern string, dir string) <span class="cov8" title="1">{
        pattern = pattern + "(.+)"
        m.AddRoute(GET, pattern, func(w http.ResponseWriter, r *http.Request) </span><span class="cov8" title="1">{
                path := filepath.Clean(r.URL.Path)
                path = filepath.Join(dir, path)
                http.ServeFile(w, r, path)
        }</span>)
}

// Filter adds the middleware filter.
func (m *RouteMux) Filter(filter http.HandlerFunc) <span class="cov8" title="1">{
        m.filters = append(m.filters, filter)
}</span>

// FilterParam adds the middleware filter iff the REST URL parameter exists.
func (m *RouteMux) FilterParam(param string, filter http.HandlerFunc) <span class="cov8" title="1">{
        if !strings.HasPrefix(param, ":") </span><span class="cov0" title="0">{
                param = ":" + param
        }</span>

        <span class="cov8" title="1">m.Filter(func(w http.ResponseWriter, r *http.Request) </span><span class="cov8" title="1">{
                p := r.URL.Query().Get(param)
                if len(p) &gt; 0 </span><span class="cov8" title="1">{
                        filter(w, r)
                }</span>
        })
}

// Adds a new Route to the Handler
func (m *RouteMux) AddRoute(method string, pattern string, handler http.HandlerFunc) <span class="cov8" title="1">{
        //split the url into sections
        parts := strings.Split(pattern, "/")

        //find params that start with ":" replace with regular expressions
        j := 0
        params := make(map[int]string)
        for i, part := range parts </span><span class="cov8" title="1">{
                if strings.HasPrefix(part, ":") </span><span class="cov8" title="1">{
                        expr := "([^/]+)"

                        if index := strings.Index(part, "("); index != -1 </span><span class="cov0" title="0">{
                                expr = part[index:]
                                part = part[:index]
                        }</span>
                        <span class="cov8" title="1">params[j] = part
                        parts[i] = expr
                        j++</span>
                }
        }

        <span class="cov8" title="1">pattern = strings.Join(parts, "/")
        regex, regexErr := regexp.Compile(pattern)
        if regexErr != nil </span><span class="cov0" title="0">{
                //TODO add error handling here to avoid panic
                panic(regexErr)</span>
                <span class="cov0" title="0">return</span>
        }

        //now create the Route
        <span class="cov8" title="1">route := &amp;route{}
        route.method = method
        route.regex = regex
        route.handler = handler
        route.params = params

        //and finally append to the list of Routes
        m.routes = append(m.routes, route)</span>
}

// Required by http.Handler interface.
// This method is invoked by the http server and will handle all page routing.
func (m *RouteMux) ServeHTTP(rw http.ResponseWriter, r *http.Request) <span class="cov8" title="1">{
        requestPath := r.URL.Path

        //wrap the response writer, in our custom interface
        w := &amp;responseWriter{writer: rw}

        //find a matching Route
        for _, route := range m.routes </span><span class="cov8" title="1">{
                if r.Method != route.method </span><span class="cov0" title="0">{
                        continue</span>
                }
                <span class="cov8" title="1">if !route.regex.MatchString(requestPath) </span><span class="cov8" title="1">{
                        continue</span>
                }

                <span class="cov8" title="1">matches := route.regex.FindStringSubmatch(requestPath)

                if len(matches[0]) != len(requestPath) </span><span class="cov0" title="0">{
                        continue</span>
                }

                <span class="cov8" title="1">if len(route.params) &gt; 0 </span><span class="cov8" title="1">{
                        values := r.URL.Query()
                        for i, match := range matches[1:] </span><span class="cov8" title="1">{
                                values.Add(route.params[i], match)
                        }</span>

                        <span class="cov8" title="1">r.URL.RawQuery = url.Values(values).Encode() + "&amp;" + r.URL.RawQuery</span>
                }

                //execute middleware filters
                <span class="cov8" title="1">for _, filter := range m.filters </span><span class="cov8" title="1">{
                        filter(w, r)
                        if w.started </span><span class="cov8" title="1">{
                                return
                        }</span>
                }

                //Invoke the request handler
                <span class="cov8" title="1">route.handler(w, r)
                break</span>
        }

        //if no matches to url, throw a not found exception
        <span class="cov8" title="1">if w.started == false </span><span class="cov8" title="1">{
                http.NotFound(w, r)
        }</span>
}


// responseWriter is a wrapper for the http.ResponseWriter to track if response was written to.
type responseWriter struct {
        writer  http.ResponseWriter
        started bool
        status  int
}

// Header returns the header map that will be sent by WriteHeader.
func (w *responseWriter) Header() http.Header <span class="cov8" title="1">{
        return w.writer.Header()
}</span>

// Write writes the data to the connection as part of an HTTP reply, and sets `started` to true
func (w *responseWriter) Write(p []byte) (int, error) <span class="cov8" title="1">{
        w.started = true
        return w.writer.Write(p)
}</span>

// WriteHeader sends an HTTP response header with status code, and sets `started` to true
func (w *responseWriter) WriteHeader(code int) <span class="cov8" title="1">{
        w.status = code
        w.started = true
        w.writer.WriteHeader(code)
}</pre>
		
		</div>
	</body>
	<script>
	(function() {
		var files = document.getElementById('files');
		var visible;
		files.addEventListener('change', onChange, false);
		function select(part) {
			if (visible)
				visible.style.display = 'none';
			visible = document.getElementById(part);
			if (!visible)
				return;
			files.value = part;
			visible.style.display = 'block';
			location.hash = part;
		}
		function onChange() {
			select(files.value);
			window.scrollTo(0, 0);
		}
		if (location.hash != "") {
			select(location.hash.substr(1));
		}
		if (!visible) {
			select("file0");
		}
	})();
	</script>
</html>
